﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Entity;
using CompanyManageSystem.Model;
using System.Collections;
using DevExpress.XtraTreeList.Nodes;
using CompanyManageSystem.Service;
using DevExpress.Utils;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraGrid.Columns;
using System.Drawing.Drawing2D;
using DevExpress.XtraTreeList;
using static CompanyManageSystem.UI.Info.Frm_AddDepartment;
using CompanyManageSystem.DLL;

namespace CompanyManageSystem.UI.Info
{
    public partial class Frm_User : BaseXtraForm
    {
        #region 构造方法
        /// <summary>
        /// 构造方法
        /// </summary>
        public Frm_User()
        {
            InitializeComponent();
        }
        #endregion

        /// <summary>
        /// 窗体加载完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Frm_User_Load(object sender, EventArgs e)
        {         
            AppService aservice = new AppService();
            treeList1.DataSource = aservice.GetDepartments();
            repositoryItemSearchLookUpEdit1.DataSource = aservice.GetDepartments();
        }

        #region 节点勾选事件
        /// <summary>
        /// 选择节点点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeList1_AfterCheckNode(object sender, DevExpress.XtraTreeList.NodeEventArgs e)
        {
            SetCheckedChildNodes(e.Node, e.Node.CheckState);
            SetCheckedParentNodes(e.Node, e.Node.CheckState);

            GetCheckedID(e.Node);

            //string id = e.Node.GetDisplayText("ID");

            //PSContext _db = new PSContext();
            //UserGrid.DataSource = _db.Users.Where(p => p.Department == id).ToList();
        }

        /// <summary>
        /// 选择某一节点时，子节点全部选择；取消时，子节点全部取消
        /// </summary>
        /// <param name="node">当前点击的节点</param>
        /// <param name="status">节点状态</param>
        private void SetCheckedChildNodes(TreeListNode node, CheckState status)
        {
            for (int i = 0; i < node.Nodes.Count(); i++)
            {
                node.Nodes[i].CheckState = status;
                //遍历下级节点
                SetCheckedChildNodes(node.Nodes[i], status);
            }
        }

        /// <summary>
        /// 子节点有一个没选中，父节点就不选中
        /// </summary>
        /// <param name="node"></param>
        /// <param name="status"></param>
        private void SetCheckedParentNodes(TreeListNode node, CheckState status)
        {
            if (node.ParentNode != null)
            {
                CheckState parentCheckStatus = node.ParentNode.CheckState;
                CheckState nodeCheckStatus;

                for (int i = 0; i < node.ParentNode.Nodes.Count; i++)
                {
                    nodeCheckStatus = node.ParentNode.Nodes[i].CheckState;
                    if (!node.Equals(nodeCheckStatus))
                    {
                        parentCheckStatus = CheckState.Unchecked;
                        break;
                    }
                    parentCheckStatus = status;
                }
                node.ParentNode.CheckState = parentCheckStatus;
                //遍历上级节点
                SetCheckedParentNodes(node.ParentNode, status);
            }
        }

        private void GetCheckedID(TreeListNode node)
        {
            if (node.CheckState == CheckState.Checked)
            {
                //Console.WriteLine(node.Id);

                //获取焦点行所在ID
                var focusDeptID = treeList1.FocusedNode.GetValue("ID");

                PSContext _db = new PSContext();
                //UserGrid.DataSource = _db.Users.Where(t => t.Department == (string)focusDeptID);

            }

        }
        #endregion

        #region 焦点行改变事件
        /// <summary>
        /// 焦点行改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeList1_FocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
        {
            AppService aservice = new AppService();

            //获取焦点行的文本信息
            var focusDeptID = treeList1.FocusedNode.GetValue("ID");

            var focusDept = treeList1.FocusedNode;

            //如果是总部门
            if (focusDept.Level == 0)
            {
                UserGrid.DataSource = aservice.GetUsers();
            }
            else
            {
                UserGrid.DataSource = aservice.GetUsersByDeparment((Guid)focusDeptID);
            }

            //改变焦点行背景色
            treeList1.Appearance.FocusedCell.BackColor = Color.LightSteelBlue;
            treeList1.Appearance.FocusedCell.BackColor2 = Color.SteelBlue;
            treeList1.OptionsView.ShowHorzLines = false;
            treeList1.OptionsView.ShowVertLines = false;
        }
        #endregion

        #region GridView指示器显示信息
        /// <summary>
        /// 方便显示信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolTipController1_GetActiveObjectInfo(object sender, DevExpress.Utils.ToolTipControllerGetActiveObjectInfoEventArgs e)
        {
            if (e.SelectedControl != UserGrid) return;

            ToolTipControlInfo info = null;

            GridView view = UserGrid.GetViewAt(e.ControlMousePosition) as GridView;

            if (view == null) return;

            GridHitInfo hi = view.CalcHitInfo(e.ControlMousePosition);

            if (hi.HitTest == GridHitTest.RowIndicator)
            {
                Object o = hi.HitTest.ToString() + hi.RowHandle.ToString();
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("基本信息");

                foreach (GridColumn col in view.Columns)
                {
                    if (col.Visible)
                    {
                        sb.AppendFormat("{0}:{1}\r\n", col.Caption, view.GetRowCellDisplayText(hi.RowHandle, col.FieldName));
                    }
                }
                info = new ToolTipControlInfo(o, sb.ToString());
            }
            if (info != null)
            {
                e.Info = info;
            }
        }

        /// <summary>
        /// 指示器事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserView_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
        {
            //e.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far;
            //if (e.Info.IsRowIndicator)
            //{
            //    if (e.RowHandle >= 0)
            //    {
            //        e.Info.DisplayText = (e.RowHandle + 1).ToString();
            //    }
            //}

        }
        #endregion

        #region 搜索功能
        /// <summary>
        /// 搜索功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Search_Click(object sender, EventArgs e)
        {
            AppService aservice = new AppService();

            //获取编辑框信息
            string text = textEdit1.Text.Trim();

            //判断是否为空
            if (!string.IsNullOrEmpty(text))
            {
                UserGrid.DataSource = aservice.GetUsersByShowText(text);
            }
            else
            {
                UserGrid.DataSource = aservice.GetUsers();
            }

        }
        #endregion

        #region 工具栏
        #region 部门
        /// <summary>
        /// 添加部门
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem4_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //获取焦点行部门ID
            var id = treeList1.FocusedNode.GetValue("ID");
                
            Frm_AddDepartment frm = new Frm_AddDepartment(status: EStatus.Add, parentID: (Guid)id);
            frm.SaveEvent += Department_AddSaveEvent;
            frm.ShowDialog();
        }
        private void Department_AddSaveEvent(object sender, EventArgs e)
        {
            AppService aservice = new AppService();
            //Department dept = sender as Department;
            //var focusNode = treeList1.FocusedNode;
            //var parentNode = focusNode.ParentNode;
            treeList1.DataSource = aservice.GetDepartments();
        }

        /// <summary>
        /// 编辑部门
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem5_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var id = treeList1.FocusedNode.GetValue("ID");
            Frm_AddDepartment frm = new Frm_AddDepartment(status:EStatus.Modify, deptID:(Guid)id);
            frm.SaveEvent += Department_UpdateSaveEvent;
            frm.ShowDialog();
        }
        private void Department_UpdateSaveEvent(object sender, EventArgs e)
        {
            AppService aservice = new AppService();
            Department dept = sender as Department;
            var deptID = treeList1.FocusedNode.GetValue("ID");
            var node = treeList1.FocusedNode;
            //更改节点文字
            node["Name"] = dept.Name;
            repositoryItemSearchLookUpEdit1.DataSource = aservice.GetDepartments();
            UserGrid.DataSource = aservice.GetUserByDepartmentID((Guid)deptID);
        }

        /// <summary>
        /// 删除部门
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem6_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            AppService aservice = new AppService();
            var node = treeList1.FocusedNode;
            var id = treeList1.FocusedNode.GetValue("ID");
            var name = treeList1.FocusedNode.GetValue("Name");

            if (DialogResult.OK == MessageBox.Show("是否删除【" + name + "】嘛?", "温馨提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information))
            {
                //确定
                aservice.DelDept((Guid)id,node);
                treeList1.DeleteNode(node);
                MessageBox.Show("删除成功");
            }
            else
            {
                //取消
            }

        }
        #endregion

        #region 用户
        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //获取焦点行的文本信息
            var focusDept = treeList1.FocusedNode.GetValue("ID");

            Frm_AddUser frm = new Frm_AddUser(departmentID: (Guid)focusDept, status: Frm_AddUser.EStatus.Add);
            frm.SaveEvent += User_AddSaveEvent;
            frm.ShowDialog();
        }
        private void User_AddSaveEvent(Object sender, EventArgs e)
        {
            //获取焦点行的文本信息
            var focusDept = treeList1.FocusedNode.GetValue("ID");

            AppService aservice = new AppService();
            UserGrid.DataSource = aservice.GetUserByDepartmentID((Guid)focusDept);

            //这里不知道需要重新加载一次SearchLookUpEdit控件的数据
            repositoryItemSearchLookUpEdit1.DataSource = aservice.GetDepartments();
        }

        /// <summary>
        /// 编辑用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //获取焦点所在节点的数据库里面对应列的信息
            var focusDept = treeList1.FocusedNode.GetValue("ID");
            var focusUser = UserView.GetFocusedRow() as Users;

            Frm_AddUser frm = new Frm_AddUser(departmentID: (Guid)focusDept, userID: focusUser.ID, status: Frm_AddUser.EStatus.Modify);
            frm.SaveEvent += User_UpdateSaveEvent;
            frm.ShowDialog();
        }
        private void User_UpdateSaveEvent(Object sender, EventArgs e)
        {
            var focusDept = treeList1.FocusedNode.GetValue("ID");

            Users user = sender as Users;
            if (user != null)
            {
                UserView.SetFocusedRowCellValue("UName", user.UName);
                UserView.SetFocusedRowCellValue("TrueName", user.TrueName);
                UserView.SetFocusedRowCellValue("IsEnabled", user.IsEnabled);
            }
            else
            {
                AppService aservice = new AppService();
                UserGrid.DataSource = aservice.GetUsersByDeparment((Guid)focusDept);
            }
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem3_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Users focusUser = UserView.GetFocusedRow() as Users;

            if (DialogResult.OK == MessageBox.Show("是否删除【" + focusUser.TrueName + "】用户嘛?", "温馨提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information))
            {
                //确定
                AppService aservice = new AppService();
                aservice.DelUser(focusUser.ID);
                UserView.DeleteRow(UserView.FocusedRowHandle);
                MessageBox.Show("删除成功!");
            }
            else
            {
                //取消
            }
        }
        #endregion

        #endregion

        #region 修改节点图标与按钮
        /// <summary>
        /// 修改节点图标
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeList1_CustomDrawNodeImages(object sender, DevExpress.XtraTreeList.CustomDrawNodeImagesEventArgs e)
        {
            if (e.Node.Nodes.Count > 0)
            {
                if (e.Node.Expanded)
                {
                    e.SelectImageIndex = 2;
                    return;
                }
                e.SelectImageIndex = 1;
            }
            else
            {
                e.SelectImageIndex = 0;
            }
        }

        /// <summary>
        /// 修改节点按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeList1_CustomDrawNodeButton(object sender, DevExpress.XtraTreeList.CustomDrawNodeButtonEventArgs e)
        {
            Rectangle rect = Rectangle.Inflate(e.Bounds, 0, -2);

            // painting background
            Brush backBrush = new LinearGradientBrush(rect, Color.Blue, Color.LightSkyBlue,
              LinearGradientMode.ForwardDiagonal);

            //填充指定矩形内部
            e.Graphics.FillRectangle(backBrush, rect);

            //绘画3D边框
            ControlPaint.DrawBorder3D(e.Graphics, rect, Border3DStyle.RaisedOuter);

            //要显示的图画
            string displayCharacter = e.Expanded ? "-" : "+";

            //水平,垂直居中
            StringFormat outCharacterFormat = new StringFormat();
            outCharacterFormat.Alignment = StringAlignment.Center;
            outCharacterFormat.LineAlignment = StringAlignment.Center;

            //绘画图标
            e.Graphics.DrawString(displayCharacter, new Font("Verdana", 8, FontStyle.Bold),
              new SolidBrush(Color.White), rect, outCharacterFormat);

            // 禁止默认的图标显示
            e.Handled = true;
        }
        #endregion

        #region 鼠标经过事件
        private void treeList1_MouseMove(object sender, MouseEventArgs e)
        {
            //TreeList _TreeView = (TreeList)sender;
            //Point mousePosition = Control.MousePosition;
            //if (_TreeView.State == TreeListState.Regular)
            //{
            //    TreeListHitInfo hitInfo = _TreeView.CalcHitInfo(new Point(e.X, e.Y));
            //    if (hitInfo.HitInfoType == HitInfoType.Cell)
            //    {
            //        //_TreeView.SetFocusedNode(hitInfo.Node);
            //        //根据鼠标的e.X和e.Y来获取TreeListNode；而不能直接通过 _TreeView.FocusedNode来获取。
            //        TreeListNode _Node = hitInfo.Node;
            //        //TreeListNode _Node = _TreeView.FocusedNode;// Winfrom 程序中这样获取的this.treeList1.GetNodeAt(e.X, e.Y);
            //        Rectangle r = (_TreeView.ViewInfo.RowsInfo[_Node].Cells[0] as DevExpress.XtraTreeList.ViewInfo.CellInfo).Bounds;
            //        if (_Node != null)
            //        {
            //            //if (!_Node.Checked)
            //            //{
            //            //防止出现闪烁。
            //            if (_TreeView.Tag == null || !_TreeView.Tag.Equals(_Node))
            //            {
            //                _TreeView.Refresh();
            //                Graphics _Graphics = Graphics.FromHwnd(_TreeView.Handle);
            //                // _Graphics.FillRectangle(new SolidBrush(Color.FromArgb(100, 0, 0, 255)), r);
            //                //重绘整行节点。
            //                _Graphics.FillRectangle(new SolidBrush(Color.FromArgb(100, 0, 0, 255)), new Rectangle(new Point(0, r.Y), new Size(_TreeView.Width, r.Height)));
            //                _Graphics.Dispose();
            //                _TreeView.Tag = _Node;
            //            }
            //            //}
            //        }
            //    }
            //}
        }






        #endregion

        /// <summary>
        /// 刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem7_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            AppService aservice = new AppService();
            treeList1.DataSource = aservice.GetDepartments();
        }
    }
}
